import tkinter as tk
from tkinter import ttk, messagebox
import sqlite3
from datetime import datetime

class SmartExpressSystem:
    def __init__(self, root):
        self.root = root
        self.root.title("智能快递管理系统")
        self.root.geometry("900x600")
        
        # 创建数据库和表
        self.create_database()
        
        # 创建界面
        self.create_widgets()
        
        # 加载快递数据
        self.load_express_data()
    
    def create_database(self):
        """创建数据库和快递信息表"""
        self.conn = sqlite3.connect('express.db')
        self.cursor = self.conn.cursor()
        
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS express (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                tracking_number TEXT NOT NULL,
                sender_name TEXT NOT NULL,
                sender_phone TEXT,
                receiver_name TEXT NOT NULL,
                receiver_phone TEXT NOT NULL,
                receiver_address TEXT NOT NULL,
                express_company TEXT,
                weight REAL,
                status TEXT DEFAULT '待揽收',
                create_time TEXT NOT NULL,
                update_time TEXT NOT NULL
            )
        ''')
        self.conn.commit()
    
    def create_widgets(self):
        """创建界面组件"""
        # 顶部标题
        title_label = tk.Label(self.root, text="智能快递管理系统", font=("微软雅黑", 20, "bold"))
        title_label.pack(pady=10)
        
        # 搜索框和按钮
        search_frame = tk.Frame(self.root)
        search_frame.pack(pady=10, fill=tk.X, padx=20)
        
        tk.Label(search_frame, text="搜索:", font=("微软雅黑", 12)).pack(side=tk.LEFT)
        
        self.search_var = tk.StringVar()
        search_entry = tk.Entry(search_frame, textvariable=self.search_var, font=("微软雅黑", 12), width=30)
        search_entry.pack(side=tk.LEFT, padx=5)
        
        search_button = tk.Button(search_frame, text="搜索", command=self.search_express, 
                                font=("微软雅黑", 12), bg="#4CAF50", fg="white")
        search_button.pack(side=tk.LEFT, padx=5)
        
        refresh_button = tk.Button(search_frame, text="刷新", command=self.load_express_data, 
                                 font=("微软雅黑", 12), bg="#2196F3", fg="white")
        refresh_button.pack(side=tk.LEFT, padx=5)
        
        # 快递信息表格
        columns = ("ID", "运单号", "寄件人", "寄件电话", "收件人", "收件电话", "收件地址", "快递公司", "重量(kg)", "状态", "创建时间")
        self.tree = ttk.Treeview(self.root, columns=columns, show="headings", height=15)
        
        # 设置列宽和标题
        col_widths = [40, 120, 80, 100, 80, 100, 150, 100, 80, 80, 150]
        for col, width in zip(columns, col_widths):
            self.tree.heading(col, text=col)
            self.tree.column(col, width=width, anchor="center")
        
        self.tree.pack(pady=10, padx=20, fill=tk.BOTH, expand=True)
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(self.tree, orient="vertical", command=self.tree.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.tree.configure(yscrollcommand=scrollbar.set)
        
        # 按钮区域
        button_frame = tk.Frame(self.root)
        button_frame.pack(pady=10)
        
        add_button = tk.Button(button_frame, text="添加快递", command=self.add_express, 
                              font=("微软雅黑", 12), bg="#FF9800", fg="white")
        add_button.pack(side=tk.LEFT, padx=10)
        
        edit_button = tk.Button(button_frame, text="修改快递", command=self.edit_express, 
                               font=("微软雅黑", 12), bg="#009688", fg="white")
        edit_button.pack(side=tk.LEFT, padx=10)
        
        delete_button = tk.Button(button_frame, text="删除快递", command=self.delete_express, 
                                 font=("微软雅黑", 12), bg="#F44336", fg="white")
        delete_button.pack(side=tk.LEFT, padx=10)
        
        status_button = tk.Button(button_frame, text="更新状态", command=self.update_status, 
                                 font=("微软雅黑", 12), bg="#673AB7", fg="white")
        status_button.pack(side=tk.LEFT, padx=10)
        
        # 绑定双击事件
        self.tree.bind("<Double-1>", self.on_tree_double_click)
    
    def load_express_data(self, search_key=None):
        """加载快递数据到表格"""
        # 清空表格
        for item in self.tree.get_children():
            self.tree.delete(item)
        
        # 查询数据
        if search_key:
            query = '''
                SELECT id, tracking_number, sender_name, sender_phone, receiver_name, 
                       receiver_phone, receiver_address, express_company, weight, 
                       status, create_time 
                FROM express 
                WHERE tracking_number LIKE ? OR sender_name LIKE ? OR receiver_name LIKE ? 
                OR receiver_phone LIKE ? OR receiver_address LIKE ?
                ORDER BY update_time DESC
            '''
            search_param = f"%{search_key}%"
            self.cursor.execute(query, (search_param, search_param, search_param, 
                                      search_param, search_param))
        else:
            query = '''
                SELECT id, tracking_number, sender_name, sender_phone, receiver_name, 
                       receiver_phone, receiver_address, express_company, weight, 
                       status, create_time 
                FROM express 
                ORDER BY update_time DESC
            '''
            self.cursor.execute(query)
        
        # 插入数据到表格
        for row in self.cursor.fetchall():
            self.tree.insert("", tk.END, values=row)
    
    def search_express(self):
        """搜索快递"""
        search_key = self.search_var.get().strip()
        if search_key:
            self.load_express_data(search_key)
        else:
            self.load_express_data()
    
    def add_express(self):
        """添加快递信息"""
        self.show_express_dialog("添加快递信息")
    
    def edit_express(self):
        """修改快递信息"""
        selected_item = self.tree.selection()
        if not selected_item:
            messagebox.showwarning("警告", "请先选择要修改的快递!")
            return
        
        item_data = self.tree.item(selected_item[0], "values")
        self.show_express_dialog("修改快递信息", item_data)
    
    def delete_express(self):
        """删除快递信息"""
        selected_item = self.tree.selection()
        if not selected_item:
            messagebox.showwarning("警告", "请先选择要删除的快递!")
            return
        
        if messagebox.askyesno("确认", "确定要删除选中的快递信息吗?"):
            item_id = self.tree.item(selected_item[0], "values")[0]
            self.cursor.execute("DELETE FROM express WHERE id=?", (item_id,))
            self.conn.commit()
            self.load_express_data()
            messagebox.showinfo("成功", "快递信息已删除!")
    
    def update_status(self):
        """更新快递状态"""
        selected_item = self.tree.selection()
        if not selected_item:
            messagebox.showwarning("警告", "请先选择要更新状态的快递!")
            return
        
        item_data = self.tree.item(selected_item[0], "values")
        current_status = item_data[9]  # 状态在第9列
        
        status_window = tk.Toplevel(self.root)
        status_window.title("更新快递状态")
        status_window.geometry("400x300")
        
        tk.Label(status_window, text="当前运单号:", font=("微软雅黑", 12)).pack(pady=5)
        tk.Label(status_window, text=item_data[1], font=("微软雅黑", 12, "bold")).pack(pady=5)
        
        tk.Label(status_window, text="当前状态:", font=("微软雅黑", 12)).pack(pady=5)
        tk.Label(status_window, text=current_status, font=("微软雅黑", 12, "bold")).pack(pady=5)
        
        tk.Label(status_window, text="选择新状态:", font=("微软雅黑", 12)).pack(pady=5)
        
        status_var = tk.StringVar(value=current_status)
        status_options = ["待揽收", "运输中", "派送中", "已签收", "退回中", "已退回"]
        
        for status in status_options:
            rb = tk.Radiobutton(status_window, text=status, variable=status_var, 
                               value=status, font=("微软雅黑", 12))
            rb.pack(anchor="w", padx=50)
        
        def save_status():
            new_status = status_var.get()
            if new_status != current_status:
                update_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                self.cursor.execute('''
                    UPDATE express SET status=?, update_time=? WHERE id=?
                ''', (new_status, update_time, item_data[0]))
                self.conn.commit()
                self.load_express_data()
                messagebox.showinfo("成功", "快递状态已更新!")
            status_window.destroy()
        
        tk.Button(status_window, text="保存", command=save_status, 
                 font=("微软雅黑", 12), bg="#4CAF50", fg="white").pack(pady=10)
    
    def on_tree_double_click(self, event):
        """双击表格查看详情"""
        item = self.tree.identify_row(event.y)
        if item:
            item_data = self.tree.item(item, "values")
            self.show_express_details(item_data)
    
    def show_express_details(self, item_data):
        """显示快递详情"""
        detail_window = tk.Toplevel(self.root)
        detail_window.title("快递详情")
        detail_window.geometry("500x400")
        
        # 创建详情内容
        details_frame = tk.Frame(detail_window, padx=20, pady=20)
        details_frame.pack(fill=tk.BOTH, expand=True)
        
        labels = [
            "运单号:", "寄件人:", "寄件电话:", "收件人:", 
            "收件电话:", "收件地址:", "快递公司:", "重量(kg):", "状态:", "创建时间:"
        ]
        
        for i, label in enumerate(labels):
            tk.Label(details_frame, text=label, font=("微软雅黑", 12), anchor="e").grid(row=i, column=0, sticky="e", pady=5)
            tk.Label(details_frame, text=item_data[i+1], font=("微软雅黑", 12), anchor="w").grid(row=i, column=1, sticky="w", pady=5)
    
    def show_express_dialog(self, title, item_data=None):
        """显示添加快递/修改快递的对话框"""
        dialog = tk.Toplevel(self.root)
        dialog.title(title)
        dialog.geometry("500x600")
        
        # 表单字段
        fields = [
            ("tracking_number", "运单号:", True),
            ("sender_name", "寄件人:", True),
            ("sender_phone", "寄件电话:", False),
            ("receiver_name", "收件人:", True),
            ("receiver_phone", "收件电话:", True),
            ("receiver_address", "收件地址:", True),
            ("express_company", "快递公司:", False),
            ("weight", "重量(kg):", False)
        ]
        
        self.entry_vars = {}
        
        for i, (field, label, required) in enumerate(fields):
            tk.Label(dialog, text=label, font=("微软雅黑", 12)).grid(row=i, column=0, padx=10, pady=5, sticky="e")
            
            var = tk.StringVar()
            if item_data:
                # 修改模式，填充现有数据
                var.set(item_data[fields.index((field, label, required)) + 1])
            
            entry = tk.Entry(dialog, textvariable=var, font=("微软雅黑", 12))
            entry.grid(row=i, column=1, padx=10, pady=5, sticky="we")
            
            if required:
                tk.Label(dialog, text="*", fg="red").grid(row=i, column=2, sticky="w")
            
            self.entry_vars[field] = var
        
        # 保存按钮
        def save_express():
            # 验证必填字段
            for field, (_, label, required) in zip(self.entry_vars.keys(), fields):
                if required and not self.entry_vars[field].get().strip():
                    messagebox.showwarning("警告", f"{label}是必填项!")
                    return
            
            # 获取表单数据
            data = {
                "tracking_number": self.entry_vars["tracking_number"].get().strip(),
                "sender_name": self.entry_vars["sender_name"].get().strip(),
                "sender_phone": self.entry_vars["sender_phone"].get().strip(),
                "receiver_name": self.entry_vars["receiver_name"].get().strip(),
                "receiver_phone": self.entry_vars["receiver_phone"].get().strip(),
                "receiver_address": self.entry_vars["receiver_address"].get().strip(),
                "express_company": self.entry_vars["express_company"].get().strip(),
                "weight": self.entry_vars["weight"].get().strip() or "0",
                "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "update_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            }
            
            try:
                data["weight"] = float(data["weight"])
            except ValueError:
                messagebox.showwarning("警告", "重量必须是数字!")
                return
            
            if item_data:
                # 修改现有记录
                self.cursor.execute('''
                    UPDATE express SET 
                        tracking_number=?, sender_name=?, sender_phone=?, 
                        receiver_name=?, receiver_phone=?, receiver_address=?, 
                        express_company=?, weight=?, update_time=?
                    WHERE id=?
                ''', (
                    data["tracking_number"], data["sender_name"], data["sender_phone"],
                    data["receiver_name"], data["receiver_phone"], data["receiver_address"],
                    data["express_company"], data["weight"], data["update_time"], item_data[0]
                ))
                message = "快递信息修改成功!"
            else:
                # 添加新记录
                self.cursor.execute('''
                    INSERT INTO express (
                        tracking_number, sender_name, sender_phone, 
                        receiver_name, receiver_phone, receiver_address, 
                        express_company, weight, status, create_time, update_time
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, '待揽收', ?, ?)
                ''', (
                    data["tracking_number"], data["sender_name"], data["sender_phone"],
                    data["receiver_name"], data["receiver_phone"], data["receiver_address"],
                    data["express_company"], data["weight"], data["create_time"], data["update_time"]
                ))
                message = "快递信息添加成功!"
            
            self.conn.commit()
            self.load_express_data()
            dialog.destroy()
            messagebox.showinfo("成功", message)
        
        save_button = tk.Button(dialog, text="保存", command=save_express, 
                               font=("微软雅黑", 12), bg="#4CAF50", fg="white")
        save_button.grid(row=len(fields), column=1, pady=20, sticky="e")
        
        # 居中显示对话框
        dialog.update_idletasks()
        width = dialog.winfo_width()
        height = dialog.winfo_height()
        x = (dialog.winfo_screenwidth() // 2) - (width // 2)
        y = (dialog.winfo_screenheight() // 2) - (height // 2)
        dialog.geometry(f"{width}x{height}+{x}+{y}")

if __name__ == "__main__":
    root = tk.Tk()
    app = SmartExpressSystem(root)
    root.mainloop()